package com.cyandpos.pad.cateringformat.choosemenu;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.changyi.device.printer.PrintManagerLib;
import com.cyandpos.pad.R;
import com.cyandpos.pad.activity.PayActivity;
import com.cyandpos.pad.cateringformat.CateringMainActivity;
import com.cyandpos.pad.cateringformat.choosemenu.presenter.QueryFoodPresenter;
import com.cyandpos.pad.cateringformat.choosemenu.presenter.QueryFoodPresenterImpl;
import com.cyandpos.pad.cateringformat.choosemenu.view.QueryFoodView;
import com.cyandpos.pad.common.commondata.CateringPosConstant;
import com.cyandpos.pad.common.commondata.Constant;
import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.common.ticketformat.TicketFormat;
import com.cyandpos.pad.login.configs.GetConfigs;
import com.cyandpos.pad.posdata.CyFood;
import com.cyandpos.pad.posdata.DjdData;
import com.cyandpos.pad.posdata.Goods;
import com.cyandpos.pad.posdata.Member;
import com.cyandpos.pad.posdata.Order;
import com.cyandpos.pad.posdata.Person;
import com.cyandpos.pad.posdata.QueryGoodParam;
import com.cyandpos.pad.posdata.QueryMemberReq;
import com.cyandpos.pad.posdata.QueryOrderReq;
import com.cyandpos.pad.posdata.SubTicketItem;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.sale.view.SelfNumKeyView;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.MoneyUtils;
import com.cyandpos.pad.utils.PayUtil;
import com.cyandpos.pad.utils.ToastUtils;
import com.cyandpos.pad.utils.log.LogUtils;
import com.cyandpos.pad.utils.view.InputNumberDialogCommon;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MenuFoodFragment extends Fragment implements View.OnClickListener, QueryFoodView {
    Unbinder unbinder;
    private View view;
    @BindView(R.id.lv_goods)
     ExpandableListView lv_goods;
    @BindView(R.id.rv_menu_type)
     RecyclerView rv_menu_type;
    @BindView(R.id.gv_menu_good)
     GridView gv_menu_good;
    @BindView(R.id.tv_sums)
     TextView tv_sums;
    @BindView(R.id.tv_discount)
     TextView tv_discount;
    @BindView(R.id.tv_all_price)
     TextView tv_all_price;
    @BindView(R.id.tv_price)
     TextView tv_price;
    @BindView(R.id.iv_function)
     ImageView iv_function;
    @BindView(R.id.tv_vip_number)
     TextView tv_vip_number;
    @BindView(R.id.tv_cent)
     TextView tv_cent;
    @BindView(R.id.tv_no_vip)
     TextView tv_no_vip;
    @BindView(R.id.tv_table)
     TextView tv_table;
    @BindView(R.id.ll_find_food)
     LinearLayout ll_find_food;
    @BindView(R.id.bt_pay)
     Button bt_pay;
    @BindView(R.id.bt_prepare)
     Button bt_prepare;
    @BindView(R.id.tv_table_person)
    TextView tv_table_person;
    private FoodOrderExpandableAdapter foodOrderAdapter;
    private List<Goods> foodOrderList;
    private FoodAdapter foodAdapter;
    private List<CyFood.CyGood> foodList;
    private FoodTypeAdapter foodTypeAdapter;
    private List<CyFood> foodTypeList;
    private ProgressDialog dialog;
    public QueryFoodPresenter queryFoodPresenter;
    public TicketInfo mTicketInfo;  //小票
    private Goods tempGoods;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        view=LayoutInflater.from(getActivity()).inflate(R.layout.fragment_food_menu,null);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    public void init(){
        queryFoodPresenter=new QueryFoodPresenterImpl(this);
        dialog = new ProgressDialog(getActivity());
        dialog.setCancelable(false);
        iv_function.setOnClickListener(this);
        ll_find_food.setOnClickListener(this);
        bt_pay.setOnClickListener(this);
        bt_prepare.setOnClickListener(this);
        tv_no_vip.setOnClickListener(this);
        LinearLayoutManager ms= new LinearLayoutManager(getActivity());
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_menu_type.setLayoutManager(ms);
        foodOrderList=new ArrayList<>();
        foodList=new ArrayList<>();
        foodTypeList=new ArrayList<>();
        mTicketInfo = ErpCommonData.ticketInfo;
        if(mTicketInfo.getSubTickets()!=null&&mTicketInfo.getSubTickets().size()>0){
            for(int i=0;i<mTicketInfo.getSubTickets().size();i++){
                mTicketInfo.getSubTickets().get(i).setSubInx(mTicketInfo.getSubTickets().get(i).getTcktInx());
                for(int j=0;j<mTicketInfo.getSubTickets().get(i).getGoodsList().size();j++){
                    foodOrderList.add(mTicketInfo.getSubTickets().get(i).getGoodsList().get(j));
                }
            }
            showOrderTotalInfo();
            setView();
            setAdPresentation(1);
            Member member=mTicketInfo.getMemberInfo();
            if (member == null) {
                mTicketInfo.setMemberInfo(null);
                tv_no_vip.setVisibility(View.VISIBLE);
                tv_vip_number.setVisibility(View.GONE);
                tv_cent.setVisibility(View.GONE);
            } else {
                mTicketInfo.setMemberInfo(member);
                tv_no_vip.setVisibility(View.GONE);
                tv_vip_number.setVisibility(View.VISIBLE);
                tv_cent.setVisibility(View.VISIBLE);
                tv_vip_number.setText("会员号："+member.getMemberCardNo());
                tv_cent.setText("积分："+member.getMemberCardValidCent());
                setAdPresentation(2);
            }
            if(getActivity() instanceof CateringMainActivity){
                ((CateringMainActivity)getActivity()).setOrderNo(mTicketInfo.getOrderNo());
            }else if(getActivity() instanceof MenuFoodActivity){
                ((MenuFoodActivity)getActivity()).setOrderNo(mTicketInfo.getOrderNo());
            }
        }else {
            if(mTicketInfo.getTableState()== CateringPosConstant.CATERING_TABLE_STATUS_USE){//就餐中
                QueryOrderReq orderReq = new QueryOrderReq(); //添加默认 查询
                orderReq.setSktno(ErpCommonData.sktno);
                orderReq.setTableNo(mTicketInfo.getTableNo());
                queryFoodPresenter.queryOrderInfoEexcute(orderReq);
            }else{
                initTicket();
                queryFoodPresenter.createSaleId("",mTicketInfo.getTableNo(),mTicketInfo.getTablePerson());
                setView();
            }
        }
        queryFoodPresenter.loadQueryFood(ErpCommonData.shopId);
        foodOrderAdapter=new FoodOrderExpandableAdapter(foodOrderList,getActivity(),this);
        lv_goods.setAdapter(foodOrderAdapter);
        lv_goods.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for(int i=0;i<lv_goods.getExpandableListAdapter().getGroupCount();i++){
                    if(i!=groupPosition){
                        lv_goods.collapseGroup(i);
                    }
                }
            }
        });
        if(getActivity() instanceof MenuFoodActivity){
            bt_prepare.setVisibility(View.VISIBLE);
        }else{
            bt_prepare.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_find_food:
                InputNumberDialogCommon dialog = InputNumberDialogCommon.getInputNumberDialogCommon(getActivity(), new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
                    @Override
                    public void InputDialogOnSubmitClick(String content) {
                        try{
                            QueryGoodParam param = new QueryGoodParam();
                            param.setBarcode(content);
                            param.setCount("1");
                            queryFoodPresenter.queryGoods(param, mTicketInfo, mTicketInfo.getSubTickets().size()-1);
                        }catch (Exception e){
                            ToastUtils.show("请输入正确的商品数量！");
                        }
                    }
                });
                dialog.setIsCanInputPoint(false);
                dialog.setTitle("商品查询");
                dialog.setContent("请输入商品代码或者商品id");
                dialog.setEtHint("请输入商品代码或者商品id");
                dialog.showDialog(false);
                break;
            case R.id.iv_function:
                showFunctionDialog();
                break;
            case R.id.bt_pay:
                upLoadGoodsPreparePay(true,new DjdData());
                break;
            case R.id.bt_prepare:
                if (mTicketInfo.getSubTickets() == null || mTicketInfo.getTicketGoodCount() <= 0) {
                    ToastUtils.showMsg("请先添加商品");
                    return;
                }
                for(int i = 0; i<GetConfigs.ticketPrintCount(); i++){
                    if (i==0){
                        List<String> list = TicketFormat.createTicketFormat(mTicketInfo,false,i);
                        PrintManagerLib.initPrinter(getActivity(), CommonUtils.getSystemModel())
                                .initDevice()
                                .printList(list);
                    }else if (i==1){
                        List<String> list = TicketFormat.createTicketFormat(mTicketInfo,false,i);
                        PrintManagerLib.initPrinter(getActivity(),CommonUtils.getSystemModel())
                                .initDevice()
                                .printList(list);

                    }else {
                        List<String> list = TicketFormat.createTicketFormat(mTicketInfo,false,-1);
                        PrintManagerLib.initPrinter(getActivity(),CommonUtils.getSystemModel())
                                .initDevice()
                                .printList(list);
                    }
                }
                ErpCommonData.ticketInfo = new TicketInfo();
//                ErpCommonData.isDJD = false;
//                ErpCommonData.isFSTH = false;
                getActivity().finish();
                break;
            case R.id.tv_no_vip:
                PayUtil.showQueryMemberDialog(getActivity(), Constant.MEMBER_IDENTIFYING_TRADE_ADD_MEMBER);
                break;
        }
    }

    @Override
    public void showProgress(String msg) {
        dialog.setMessage(msg);
        dialog.show();
    }

    @Override
    public void dismissProgress() {
        dialog.dismiss();
    }

    @Override
    public void QueryFoodSuccess(List<CyFood> FoodList) {
        if(FoodList!=null&&FoodList.size()>0) {
            foodTypeList = FoodList;
            foodList = foodTypeList.get(0).getGoodsList();
            if(foodList!=null&&foodList.size()>0) {
                foodAdapter = new FoodAdapter(foodList, getActivity());
                gv_menu_good.setAdapter(foodAdapter);
            }else{
                ToastUtils.show("该分类下无餐品");
            }
            gv_menu_good.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    QueryGoodParam param = new QueryGoodParam();
                    param.setGoodsId(foodList.get(position).getSpid()+"");
                    param.setCount("1");
//                    queryFoodPresenter.queryGoods(foodList.get(position).getSpid() + "*", mTicketInfo, mTicketInfo.getSubTickets().size() - 1);
                    queryFoodPresenter.queryGoods(param, mTicketInfo, mTicketInfo.getSubTickets().size() - 1);
                }
            });
            foodTypeAdapter = new FoodTypeAdapter(foodTypeList, getActivity());
            rv_menu_type.setAdapter(foodTypeAdapter);
            foodTypeAdapter.setOnItemClickListener(new FoodTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    foodTypeAdapter.setIndex(position);
                    foodList = foodTypeList.get(position).getGoodsList();

                        foodAdapter = new FoodAdapter(foodList, getActivity());
                        gv_menu_good.setAdapter(foodAdapter);
                   
                }
            });
        }else{
             ToastUtils.show("暂无餐品!");
        }
    }

    @Override
    public void QueryFoodFailure(String errorMsg) {
        ToastUtils.show(errorMsg);
    }

    @Override
    public void createOrderNO(String order) {
        ErpCommonData.orderNo = order;
        mTicketInfo.setOrderNo(order);
        if(getActivity() instanceof CateringMainActivity){
            ((CateringMainActivity)getActivity()).setOrderNo(order);
        }else if(getActivity() instanceof MenuFoodActivity){
            ((MenuFoodActivity)getActivity()).setOrderNo(order);
        }
    }

    @Override
    public void handleGoods(Goods goods) {
        tempGoods = goods;
        if (tempGoods.getClassType().equals("1") && tempGoods.getPrice().equals("0")) {// 大类或细类_需输入售价
            InputNumberDialogCommon dialog = InputNumberDialogCommon.getInputNumberDialogCommon(getActivity(), new InputNumberDialogCommon.InputDialogOnSubmitClickListener() {
                @Override
                public void InputDialogOnSubmitClick(String content) {
                    try{
//                        content = content + "|" + tempGoods.getSaleCount() + "|" + tempGoods.getBarCode() + "|" + tempGoods.getGoodsGuid();
                        QueryGoodParam param = new QueryGoodParam();
                        param.setBarcode(tempGoods.getBarcode());
                        param.setCount(tempGoods.getSaleCount());
                        param.setGoodsGuid(tempGoods.getGoodsGuid());
                        param.setGoodsPrice(content);
                        queryFoodPresenter.queryGoods(param, mTicketInfo, mTicketInfo.getSubTickets().size()-1);
                    }catch (Exception e){
                        ToastUtils.show("请输入正确的商品价格！");
                    }
                }
            });
            dialog.setIsCanInputPoint(true);
            dialog.setTitle("商品价格");
            dialog.setContent("请输入商品价格");
            dialog.setEtHint("请输入商品价格");
            dialog.showDialog(false);
        } else {
            addGoodsToTicket(false);
        }
    }

    @Override
    public void frontDiscount(List<Goods> goods, boolean isSingle) {
        List<Goods> newGoods=new ArrayList<>();
        for(int i=goods.size()-1;i>=0;i--){
            newGoods.add(goods.get(i));
        }
        mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).setGoodsList(newGoods);
        foodOrderList.clear();
        for(int i =0;i< mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().size();i++){
            foodOrderList.add(mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().get(i).goodClone());
        }
        foodOrderAdapter.setNewData(foodOrderList);
       setAdPresentation(1);
        showOrderTotalInfo();
    }

    @Override
    public void addMember(Member member) {
        if (member == null) {
            mTicketInfo.setMemberInfo(null);
            tv_no_vip.setVisibility(View.VISIBLE);
            tv_vip_number.setVisibility(View.GONE);
            tv_cent.setVisibility(View.GONE);
        } else {
            mTicketInfo.setMemberInfo(member);
            tv_no_vip.setVisibility(View.GONE);
            tv_vip_number.setVisibility(View.VISIBLE);
            tv_cent.setVisibility(View.VISIBLE);
            tv_vip_number.setText("会员号："+member.getMemberCardNo());
            tv_cent.setText("积分："+member.getMemberCardValidCent());
            setAdPresentation(2);
        }
    }

    @Override
    public void cancelOrder(String orderNo) {
//        tv_no_vip.setVisibility(View.VISIBLE);
//        tv_vip_number.setVisibility(View.GONE);
//        tv_cent.setVisibility(View.GONE);
        ErpCommonData.ticketInfo = new TicketInfo();
//        initTicket();
//        foodOrderList.clear();
//        foodOrderAdapter.setNewData(foodOrderList);

//        ErpCommonData.isDJD = false;
//        ErpCommonData.isFSTH = false;

//        queryFoodPresenter.createSaleId("");
//        setAdPresentation(4);
        getActivity().finish();
    }

    @Override
    public void preparePay(TicketInfo ticketInfo, boolean isPromotion) {
        if(isPromotion){
            ErpCommonData.ticketInfo = ticketInfo;
            showOrderPreferentialInto(ticketInfo);
        }else{
            ErpCommonData.ticketInfo = ticketInfo;
            Bundle bundle = new Bundle();
            bundle.putInt("SaleType", 0);
            bundle.putInt("fromType", 1);
            Intent intent  = new Intent(getActivity(),PayActivity.class);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            startActivity(intent);
            getActivity().overridePendingTransition(0, 0);
        }
    }

    /**
     * 查询订单
     * @param orderList
     * @param orderCount
     */
    @Override
    public void queryOrder(List<Order> orderList, double orderCount) {
        if(orderList.get(0).getSubTickets()!=null&&orderList.get(0).getSubTickets().size()>0) {
            for (int i = 0; i < orderList.get(0).getSubTickets().size(); i++) {
                orderList.get(0).getSubTickets().get(i).setSubInx(orderList.get(0).getSubTickets().get(i).getTcktInx());
            }
            mTicketInfo.setSubTickets(orderList.get(0).getSubTickets());
        }else{
            SubTicketItem subTicketItem = new SubTicketItem();
            subTicketItem.setSubInx("0");
            subTicketItem.setPersonInfo(orderList.get(0).getCasherInfo());
            mTicketInfo.getSubTickets().clear();
            mTicketInfo.getSubTickets().add(subTicketItem);
        }
        mTicketInfo.setOfferCouponList(orderList.get(0).getOfferCouponList());
        mTicketInfo.setPayList(orderList.get(0).getPayList());
        mTicketInfo.setLottoList(orderList.get(0).getLottoList());
        mTicketInfo.setCasherInfo(orderList.get(0).getCasherInfo());
        mTicketInfo.setMemberInfo(orderList.get(0).getMemberInfo());
        mTicketInfo.setJlbh(orderList.get(0).getJlbh());
        mTicketInfo.setOrderNo(orderList.get(0).getOrderNo());
        mTicketInfo.setOrderTime(orderList.get(0).getOrderTime());
        mTicketInfo.setTableNo(orderList.get(0).getTableId()+"");
        mTicketInfo.setTablePerson(orderList.get(0).getMealsCount()+"");
        for(int i=0;i<mTicketInfo.getSubTickets().size();i++){
            for(int j=0;j<mTicketInfo.getSubTickets().get(i).getGoodsList().size();j++){
                foodOrderList.add(mTicketInfo.getSubTickets().get(i).getGoodsList().get(j));
            }
        }
        showOrderTotalInfo();
        setView();
        foodOrderAdapter=new FoodOrderExpandableAdapter(foodOrderList,getActivity(),this);
        lv_goods.setAdapter(foodOrderAdapter);
        setAdPresentation(1);
        Member member=mTicketInfo.getMemberInfo();
        if (member == null) {
            mTicketInfo.setMemberInfo(null);
            tv_no_vip.setVisibility(View.VISIBLE);
            tv_vip_number.setVisibility(View.GONE);
            tv_cent.setVisibility(View.GONE);
        } else {
            mTicketInfo.setMemberInfo(member);
            tv_no_vip.setVisibility(View.GONE);
            tv_vip_number.setVisibility(View.VISIBLE);
            tv_cent.setVisibility(View.VISIBLE);
            tv_vip_number.setText("会员号："+member.getMemberCardNo());
            tv_cent.setText("积分："+member.getMemberCardValidCent());
            setAdPresentation(2);
        }
        if(getActivity() instanceof CateringMainActivity){
            ((CateringMainActivity)getActivity()).setOrderNo(mTicketInfo.getOrderNo());
        }else if(getActivity() instanceof MenuFoodActivity){
            ((MenuFoodActivity)getActivity()).setOrderNo(mTicketInfo.getOrderNo());
        }
    }


    private void initTicket() {
        mTicketInfo.setOrderNo("");
        mTicketInfo.setSktno(ErpCommonData.sktno);
        mTicketInfo.setStoreCode(ErpCommonData.storeCode);
        Person person = new Person();
        person.setPersonCode(ErpCommonData.loadConfig.getCashierCode());
        person.setPersonId(Integer.valueOf(ErpCommonData.loadConfig.getCashierId()));
        person.setPersonName(ErpCommonData.loadConfig.getCashierName());
        person.setPersonDeptCode(ErpCommonData.loadConfig.getCashierDeptCode());
        person.setPersonDeptId(Integer.valueOf(ErpCommonData.loadConfig.getCashierDeptId()));
        person.setPersonDeptName(ErpCommonData.loadConfig.getCashierDeptName());
        person.setShopId(0);
        SubTicketItem subTicketItem = new SubTicketItem();
        subTicketItem.setSubInx("0");
        subTicketItem.setPersonInfo(person);
        mTicketInfo.getSubTickets().clear();
        mTicketInfo.getSubTickets().add(subTicketItem);
        mTicketInfo.setCasherInfo(person);
//        ErpCommonData.isFSTH = false;
//        ErpCommonData.isDJD = false;
        showOrderTotalInfo();
    }

    /**
     *
     * @param isSuspendOrderRefresh 是否是挂单刷新界面
     */
    private void addGoodsToTicket(boolean isSuspendOrderRefresh) {
        ToastUtils.show("操作商品成功");
        LogUtils.d("当前子小票的长度:" + mTicketInfo.getSubTickets().size());
        boolean isGoods = false;//是否直接添加商品标志
        if(!isSuspendOrderRefresh){
            subFlag:
            for (int i = 0; i < mTicketInfo.getSubTickets().size(); i++) {
                SubTicketItem itemSub = mTicketInfo.getSubTickets().get(i);
                if (itemSub.getGoodsList().size() <= 0) {
                    isGoods = true;
                    itemSub.getGoodsList().add(tempGoods);
                    break;
                }
                for (Goods g : itemSub.getGoodsList()) {
                    if (tempGoods.getGoodsGuid().equals(g.getGoodsGuid())) {
                        isGoods = true;
                        if (tempGoods.getSaleCount().equals("0")) {
                            itemSub.getGoodsList().remove(g);
                            break subFlag;
                        }
                        g.setSaleCount(tempGoods.getSaleCount());
                        g.setSaleMoney(tempGoods.getSaleMoney());
                        g.setDiscount(tempGoods.getDiscount());
                        g.setPreferentialMoney(tempGoods.getPreferentialMoney());
                        break subFlag;
                    }
                }
            }
            if (!isGoods) {
                mTicketInfo.getSubTickets().get(mTicketInfo.getSubTickets().size() - 1).getGoodsList().add(tempGoods);
            }
        }
        foodOrderList.clear();
        for (int i = mTicketInfo.getSubTickets().size()-1; i >= 0; i--) {
            SubTicketItem item = mTicketInfo.getSubTickets().get(i);
            LogUtils.d("当前子小票商品列表长度:" + item.getGoodsList().size());
            for(int j = 0 ; j < item.getGoodsList().size(); j++){
                foodOrderList.add(item.getGoodsList().get(j).goodClone());
            }
        }
        foodOrderAdapter.setNewData(foodOrderList);
        for(int i=0;i<lv_goods.getExpandableListAdapter().getGroupCount();i++){
            lv_goods.collapseGroup(i);
        }
        showOrderTotalInfo();
        setAdPresentation(1);
    }


    private void showOrderTotalInfo() {
        double totalNum = 0;
        int totalPrice = 0;
        int totalDiscount = 0;
        for (SubTicketItem sub : mTicketInfo.getSubTickets()) {
            totalPrice += sub.getTotalMoney();
            totalDiscount += sub.getTotalDiscount();
            for (Goods g : sub.getGoodsList()) {
                totalNum += MoneyUtils.getStrToDouble(g.getSaleCount());
            }
        }
        int payableAmt = totalPrice - totalDiscount;
        tv_sums.setText("总数量：" + totalNum);
        tv_all_price.setText("总价："+MoneyUtils.getMoneyStr(totalPrice));
        tv_discount.setText("总优惠："+MoneyUtils.getMoneyStr(totalDiscount));
        tv_price.setText("应收："+MoneyUtils.getMoneyStr(totalPrice-totalDiscount));
    }

    public void showFunctionDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        final AlertDialog functionDialog=builder.create();
        View view= LayoutInflater.from(getActivity()).inflate(R.layout.dialog_function,null);
        RelativeLayout rl_close=view.findViewById(R.id.rl_close);
        LinearLayout ll_order_cancle=view.findViewById(R.id.ll_order_cancle);
        LinearLayout ll_discount=view.findViewById(R.id.ll_discount);
        LinearLayout ll_vip=view.findViewById(R.id.ll_vip);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionDialog.dismiss();
            }
        });
        ll_order_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionDialog.dismiss();
                queryFoodPresenter.cancelOrder(mTicketInfo.getOrderNo());
            }
        });
        ll_discount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionDialog.dismiss();
                handleFullOrderDiscount();
            }
        });
        ll_vip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionDialog.dismiss();
                PayUtil.showQueryMemberDialog(getActivity(), Constant.MEMBER_IDENTIFYING_TRADE_ADD_MEMBER);
            }
        });
        functionDialog.setView(view,0,0,0,0);
        functionDialog.show();
        functionDialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_flavor_bg);
    }

    /**
     * 整单折扣
     */
    private void handleFullOrderDiscount() {
        if (mTicketInfo.getSubTickets() == null || mTicketInfo.getSubTickets().get(0).getGoodsList().size() <= 0) {
            ToastUtils.showMsg("请先添加商品");
        }else{
            int orderTotalMoney =0;
            for(SubTicketItem item : mTicketInfo.getSubTickets()){
                for(Goods g : item.getGoodsList()){
                    orderTotalMoney += MoneyUtils.getMoneyInt(g.getSaleMoney());
                }
            }
            showFrontDiscountDialog(mTicketInfo,orderTotalMoney);
        }
    }


    /**
     * 整单折扣弹框
     * @param mTicketInfo
     * @param orderTotalMoney
     */
    public  void showFrontDiscountDialog( final TicketInfo mTicketInfo, final int orderTotalMoney) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final AlertDialog dialog=builder.create();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_goods_frontdiscount, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        final SelfNumKeyView sf_containt = view.findViewById(R.id.member_soft_keyboard);

        tvTitle.setText("整单折扣");
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); //textview的drawableRight

        RadioButton rb_zkl = view.findViewById(R.id.rb_frontDiscount_zkl);//折扣率
        final RadioButton rb_zke = view.findViewById(R.id.rb_frontDiscount_zke);//折扣额
        TextView tv_payMoney = view.findViewById(R.id.tv_frontDiscount_payMoney);//应付金额
        final TextView tv_actuallyMoney = view.findViewById(R.id.tv_frontDiscount_actuallyMoney);//实付金额
        final TextView tv_discountType = view.findViewById(R.id.tv_zkType_name);//折扣名称
        final ImageView iv_discountRate = view.findViewById(R.id.iv_discountRate);//折扣率图片
        final EditText etDiscountRate = view.findViewById(R.id.et_frontDiscount_discountRate);//et折扣率
        final TextView tvDiscountRate = view.findViewById(R.id.tv_frontDiscount_discountRate);//et折扣率
        Button btnSure = view.findViewById(R.id.btn_frontDiscount_ok);//确定
        Button btnCancel = view.findViewById(R.id.btn_frontDiscount_cancel);//退出

        tv_payMoney.setText("￥"+ MoneyUtils.getMoneyStr(orderTotalMoney)+"");
        tv_actuallyMoney.setText("￥"+MoneyUtils.getMoneyStr(orderTotalMoney)+"");
        rb_zke.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折扣金额");
                iv_discountRate.setVisibility(View.GONE);

            }
        });

        rb_zkl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_discountType.setText("折  扣  率");
                iv_discountRate.setVisibility(View.VISIBLE);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });


        etDiscountRate.setFocusable(false);
        sf_containt.setEnterReceptor(etDiscountRate);
        sf_containt.setIsCanInputPoint(true);
        sf_containt.setOnCallBack(new SelfNumKeyView.SelfNumCallBack() {
            @Override
            public void keyBoardSure(String num,String hint) {
                int zkje = 0;
                if(rb_zke.isChecked()){//折扣额
                    if(calculateFront(mTicketInfo,1,num,orderTotalMoney)!=null){
                        zkje = Integer.parseInt(calculateFront(mTicketInfo,0,num,orderTotalMoney));
                        tv_actuallyMoney.setText("￥"+MoneyUtils.getMoneyStr(orderTotalMoney -
                                zkje)+"");
                    }
                }else{//折扣率
                    if(calculateFront(mTicketInfo,0,num,orderTotalMoney)!=null){
                        zkje = Integer.parseInt(calculateFront(mTicketInfo,0,num,orderTotalMoney));
                        tv_actuallyMoney.setText("￥"+MoneyUtils.getMoneyStr(orderTotalMoney -
                                zkje)+"");
                    }
                }

            }
        });

        etDiscountRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtils.hideSoftInputButWithSelection(etDiscountRate,getActivity());
                etDiscountRate.setFocusable(true);
                etDiscountRate.setFocusableInTouchMode(true);
                etDiscountRate.requestFocus();

            }
        });

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                int disType =0;
                String discountInputContext = etDiscountRate.getText().toString();
                if(rb_zke.isChecked()){
                    disType =1;
                }else{
                    double tempDiscountRate = Double.valueOf(etDiscountRate.getText().toString())/10;
                    LogUtils.d("折扣率为："+tempDiscountRate);
                    discountInputContext = tempDiscountRate +"";
                }
                if(calculateFront(mTicketInfo,disType,etDiscountRate.getText().toString(),orderTotalMoney)!=null)
                    queryFoodPresenter.frontDiscount(disType+"",discountInputContext,null,mTicketInfo.getOrderNo(),false);
            }
        });

        dialog.setView(view,0,0,0,0);
        dialog.setCancelable(false);
        dialog.show();
    }

    private static String calculateFront(TicketInfo mTicketInfo,int disType, String discount,int totalMoney){
        String zkje ="0";
        if (TextUtils.isEmpty(discount) || discount == null){
            return null;
        }
        if(disType == 0){//折扣率
            double tempDiscountRate = Double.valueOf(discount)/100;
            if (tempDiscountRate <= 0 || tempDiscountRate >= 1) {
                ToastUtils.showMsg("请输入正确折扣率", 0);
                return null;
            }
            zkje =  MoneyUtils.Double2Int(totalMoney/100 * (1 - tempDiscountRate))+"";
        }else {
            int tempDiscount = MoneyUtils.getMoneyInt(discount);
            int goodSumMoney = totalMoney;
            if(tempDiscount>goodSumMoney){
                ToastUtils.showMsg("折扣金额不能大于销售金额",0);
                return null;
            }
            zkje = MoneyUtils.getMoneyInt(discount)+"";
        }
        return zkje;
    }

    /**
     *
     * @param isPromotion 是否是调用预算接口
     */
    public void upLoadGoodsPreparePay(boolean isPromotion, DjdData djdData) {
        if (mTicketInfo.getSubTickets() == null || mTicketInfo.getTicketGoodCount() <= 0) {
            ToastUtils.showMsg("请先添加商品");
            return;
        }

        if (ErpCommonData.loadConfig.getPayList() == null || ErpCommonData.loadConfig.getPayList().size() <= 0) {
            ToastUtils.showMsg("此款台没有收款方式，请查看后重新录入！");
            return;
        }
        queryFoodPresenter.preparePay(mTicketInfo, isPromotion);
    }

    /**
     * 预算后订单信息弹框
     *
     * @param ticketInfo
     */
    public  void  showOrderPreferentialInto(final TicketInfo ticketInfo) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final AlertDialog dialog=builder.create();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_order_budget_info, null);
        TextView tvTitle = view.findViewById(R.id.tv_dialog_title_name);
        tvTitle.setText("整单促销计算");
        tvTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); //textview的drawableRight

        TextView tv_totalMoney = view.findViewById(R.id.tv_budget_order_totalMoney);//总价
        TextView tv_discountMoney= view.findViewById(R.id.tv_budget_order_discountMoney);//折扣
        TextView tv_actualPayMoney= view.findViewById(R.id.tv_budget_order_actualPayMoney);//实付
        TextView tv_taxMone = view.findViewById(R.id.tv_budget_order_taxMoney);//税额

        Button btnSure = view.findViewById(R.id.btn_budget_ok);//确定
        Button btnCancel = view.findViewById(R.id.btn_budget_back);//返回


        LogUtils.d("总价："+ticketInfo.getTotalAmount() );
        tv_totalMoney.setText( MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalAmount()) + MoneyUtils.getMoneyInt(ticketInfo.getTotalDiscount()) ));
        tv_discountMoney.setText(MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalDiscount())));
        tv_actualPayMoney.setText( MoneyUtils.getMoneyStr(MoneyUtils.getMoneyInt(ticketInfo.getTotalAmount())));
        tv_taxMone.setText(MoneyUtils.getMoneyStr(0)+"");


        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                DjdData djdData = new DjdData();
                upLoadGoodsPreparePay(false,djdData);
            }
        });


        dialog.setView(view,0,0,0,0);
        dialog.setCancelable(false);
        dialog.show();
    }

    public void queryMember(QueryMemberReq requestParam){
        queryFoodPresenter.queryMember(requestParam);
    }

    /**
     * 副显数据
     * @param type
     */
    public void setAdPresentation(int type){
        switch (type){
            case 1:
                if(getActivity() instanceof CateringMainActivity) {
                    if(((CateringMainActivity) getActivity()).adPresentationUtil!=null) {
                        if (((CateringMainActivity) getActivity()).adPresentationUtil.getMode() == 0) {
                            ((CateringMainActivity) getActivity()).adPresentationUtil.setMode(1);
                        }
                        ((CateringMainActivity) getActivity()).adPresentationUtil.addGoods(foodOrderList);
                    }
                }else if(getActivity() instanceof MenuFoodActivity){
                    if(((MenuFoodActivity) getActivity()).adPresentationUtil!=null) {
                        if (((MenuFoodActivity) getActivity()).adPresentationUtil.getMode() == 0) {
                            ((MenuFoodActivity) getActivity()).adPresentationUtil.setMode(1);
                        }
                        ((MenuFoodActivity) getActivity()).adPresentationUtil.addGoods(foodOrderList);
                    }
                }
                break;
            case 2:
                if(getActivity() instanceof CateringMainActivity) {
                    if(((CateringMainActivity) getActivity()).adPresentationUtil!=null) {
                        ((CateringMainActivity) getActivity()).adPresentationUtil.addMember(mTicketInfo.getMemberInfo());
                    }
                }else if(getActivity() instanceof MenuFoodActivity){
                    if(((MenuFoodActivity) getActivity()).adPresentationUtil!=null) {
                        ((MenuFoodActivity) getActivity()).adPresentationUtil.addMember(mTicketInfo.getMemberInfo());
                    }
                }
                break;
            case 4:
                if(getActivity() instanceof CateringMainActivity) {
                    if(((CateringMainActivity) getActivity()).adPresentationUtil!=null) {
                        ((CateringMainActivity) getActivity()).adPresentationUtil.setMode(0);
                    }
                }else if(getActivity() instanceof MenuFoodActivity){
                    if(((MenuFoodActivity) getActivity()).adPresentationUtil!=null) {
                        ((MenuFoodActivity) getActivity()).adPresentationUtil.setMode(0);
                    }
                }
                break;
        }
    }
  public void cancleOrder(){
      queryFoodPresenter.cancelOrder(mTicketInfo.getOrderNo());
  }

  public void finish(){
      ErpCommonData.ticketInfo = new TicketInfo();
//      ErpCommonData.isDJD = false;
//      ErpCommonData.isFSTH = false;
      getActivity().finish();
  }

  public void setView(){
        if(mTicketInfo.getTableNo()!=null&&!"".equals(mTicketInfo.getTableNo())) {
            tv_table.setText(mTicketInfo.getTableNo() + "号桌");
            tv_table.setVisibility(View.VISIBLE);
        }else{
            tv_table.setVisibility(View.GONE);
        }
        if(mTicketInfo.getTablePerson()!=null&&!"".equals(mTicketInfo.getTablePerson())) {
            tv_table_person.setText("就餐人数：" + mTicketInfo.getTablePerson());
            tv_table_person.setVisibility(View.VISIBLE);
        }else{
            tv_table_person.setVisibility(View.GONE);
        }
  }
}
